package Thread;

// 定义两个线程，并发的对一个变量自增 5w 次，共自增 10w 次

class Counter{
    public int count;

//    public synchronized void increase() {
//        count++;
//    }
    // 针对 this加锁(可以创建出多个实例)
    // 若synchronized修饰static，则针对类对象加锁，整个JVM里只有一个

    public void increase() {
        synchronized (this) { // 给 counter对象(以下new的实例)加锁,多线程访问调用 increase访问counter需要加锁等待
            count++;
        }
    }
    // 上面两种写法是等价的
}

public class Demo13 {
    private static Counter counter = new Counter();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });

        t1.start();
        t2.start();


        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(counter.count);
    }
}
